import os
import sys
from typing import List, Callable
from loguru import logger
from conf.config import app_config

LOG_LEVEL_NAME_ID = {
    'TRACE': 5,
    'DEBUG': 10,
    'INFO': 20,
    'SUCCESS': 25,
    'WARNING': 30,
    'ERROR': 40,
    'CRITICAL': 50,
}


def make_filter(name: str, log_level: List[str]) -> Callable:
    if len(log_level) != 2:
        log_level = ['TRACE', 'CRITICAL']
    log_level_min = LOG_LEVEL_NAME_ID.get(log_level[0], 5)
    log_level_max = LOG_LEVEL_NAME_ID.get(log_level[1], 50)

    def filter(record):
        level_no = record["level"].no
        level_passed = log_level_min <= level_no <= log_level_max
        return level_passed and record["extra"].get("name", "") == name

    return filter


logger.remove()
logger.level('NULL', no=999, color='', icon='')
# 调试环境日志, 输出到控制台
app_config.DEBUG and logger.add(
    sys.stdout,
    level='DEBUG',
    format=app_config.LOG_FORMAT,
    enqueue=True
)

# 默认日志: logger.warning('...')
logger.add(
    os.path.join(app_config.LOG_DEFAULT_PATH, app_config.LOG_DEFAULT_FILENAME),
    rotation=app_config.LOG_ROTATION,
    encoding="utf-8",
    level=app_config.LOG_DEFAULT_LEVEL,
    format=app_config.LOG_FORMAT,
    enqueue=True
)
# 管理日志: admin_logger.warning('...')
admin_logger = logger.bind(name="admin")
admin_logger.add(
    os.path.join(app_config.ADMIN_LOG_PATH, app_config.LOG_STDOUT_FILENAME),
    rotation=app_config.LOG_ROTATION,
    encoding="utf-8",
    level=app_config.LOG_LEVEL,
    format=app_config.LOG_FORMAT,
    enqueue=True,
    filter=make_filter("admin", ["DEBUG", "WARNING"])
)
admin_logger.add(
    os.path.join(app_config.ADMIN_LOG_PATH, app_config.LOG_STDERR_FILENAME),
    rotation=app_config.LOG_ROTATION,
    encoding="utf-8",
    level=app_config.LOG_LEVEL,
    format=app_config.LOG_FORMAT,
    enqueue=True,
    filter=make_filter("admin", ["ERROR", "CRITICAL"])
)

api_logger = logger.bind(name="api")
api_logger.add(
    os.path.join(app_config.API_LOG_PATH, app_config.LOG_STDOUT_FILENAME),
    rotation=app_config.LOG_ROTATION,
    encoding="utf-8",
    level=app_config.LOG_LEVEL,
    format=app_config.LOG_FORMAT,
    enqueue=True,
    filter=make_filter("api", ["DEBUG", "SUCCESS"])
)
api_logger.add(
    os.path.join(app_config.API_LOG_PATH, app_config.LOG_STDERR_FILENAME),
    rotation=app_config.LOG_ROTATION,
    encoding="utf-8",
    level=app_config.LOG_LEVEL,
    format=app_config.LOG_FORMAT,
    enqueue=True,
    filter=make_filter("api", ["WARNING", "CRITICAL"])
)




